package com.xsq.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class Util {

	/**
	 * 新的md5签名，首尾放secret。
	 * 
	 * @param secret 分配给您的APP_SECRET
	 */
	public static String md5Signature(TreeMap<String, String> params, String secret) {
		String result = null;
		StringBuffer orgin = getBeforeSign(params, new StringBuffer(secret));
		if (orgin == null){
			return result;
		}
		orgin.append(secret);
		//System.out.println("before MD5:"+orgin.toString());
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
		} catch (Exception e) {
			throw new RuntimeException("sign error !");
		}
		return result;
	}

	public static void main(String[] args) {
		String result = null;
		String orgin = "7e374d265e42324967a0b12ce2d4e077appKey20161115154018375003formatxmllocalezh_CNmethodgetUsercodesByOrgidrequest_xml<?xml version=\"1.0\" encoding=\"utf-8\"?><query_usercodes><orgid>160097</orgid></query_usercodes>sign_methodmd5v1.07e374d265e42324967a0b12ce2d4e077";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
		} catch (Exception e) {
			throw new RuntimeException("sign error !");
		}
		System.out.println(result);
		
	}
	/**
	 * 二行制转字符串
	 */
	private static String byte2hex(byte[] b) {
		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs.append("0").append(stmp);
			else
				hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}

	
	
	/**
	 * 添加参数的封装方法
	 */
	private static StringBuffer getBeforeSign(TreeMap<String, String> params, StringBuffer orgin) {
		if (params == null)
			return null;
		Map<String, String> treeMap = new TreeMap<String, String>();
		treeMap.putAll(params);
		Iterator<String> iter = treeMap.keySet().iterator();
		while (iter.hasNext()) {
			String name = (String) iter.next();
			orgin.append(name).append(params.get(name));
		}
		return orgin;
	}
	
	private static final int CONNECT_TIMEOUT = 1000;
    private static final int READ_TIMEOUT = 2000;

	/** 连接到TOP服务器并获取数据 */
	public static String getResult(String urlStr, String content) {
		

		URL url = null;
		HttpURLConnection connection = null;

		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			
			connection.setConnectTimeout(CONNECT_TIMEOUT); //连接主机超时（单位：毫秒）
			connection.setReadTimeout(READ_TIMEOUT); //从主机读取数据超时（单位：毫秒）
			connection.setInstanceFollowRedirects(false);
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
			
			connection.connect();

			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			if(content!=null && !content.isEmpty()){
				out.write(content.getBytes("utf-8"));
				out.flush();
				out.close();
			}
			
		
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			return buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return null;
	}
}
